package nc.bs.arap.plugin;

import com.alibaba.fastjson.JSONObject;
import com.dq.demos.web.utils.HttpUtils;
import nc.bs.arap.invoice.util.InvoiceOfdUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.logging.Logger;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.pubitf.para.SysInitQuery;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 发票下载
 * @author Administrator
 *  nc.bs.arap.plugin.ArapFileDownlLoadYFKPlugin
 */
public class ArapFileDownlLoadYFKPlugin implements IBackgroundWorkPlugin {

	private BaseDAO dao = new BaseDAO();
	private String uri;
	private String pathname;
	private String date;

	@Override
	public PreAlertObject executeTask(BgWorkingContext bwc)
			throws BusinessException {

		HttpURLConnection connection = null;
		BufferedReader reader = null;
		OutputStream dataout = null;
		try {
			LinkedHashMap<String, Object> keyMap = bwc.getKeyMap();

			Object date = new UFDate().getDateBefore(1).toStdString();
			String type = (String)keyMap.get("type");
			if(type == null){
				throw new Exception("附件下载日期类型不能为空，请检查后台任务中的参数设置-type");
			}
			if("02".equals(type)){
				date = keyMap.get("date");
				if(date == null || date.toString().trim().length() == 0){
					throw new Exception("附件下载日期不能为空，请检查后台任务中的参数设置-date");
				}
			}
			Object date2 = null;
			if("03".equals(type)){
				date = keyMap.get("date");
				if(date == null || date.toString().trim().length() == 0){
					throw new Exception("附件下载日期不能为空，请检查后台任务中的参数设置-date");
				}

				date2 = keyMap.get("date2");
				if(date == null || date.toString().trim().length() == 0){
					throw new Exception("附件下载起始日期不能为空，请检查后台任务中的参数设置-date");
				} 
			}
			UFDate start_date = new UFDate(date.toString());
			UFDate end_date = start_date;
			if(date2 != null){
				end_date = new UFDate(date2.toString());
			}
			JSONObject param = new JSONObject();
			param.put("beginDate", start_date.toString());
			param.put("endDate",end_date.toString());
			param.put("reqURL","");
			String tbjipprot = SysInitQuery.getParaString("GLOBLE00000000000000", "tbjipprot");
			String YFKURL = "http://"+tbjipprot+"/ToYFKService/fpUpload";
			HttpUtils.sendPost(YFKURL, param.toString());
		} catch (Exception e) {
			Logger.error("浙里办票下载附件出现异常了");
			Logger.error(e);
			ExceptionUtils.wrappException(e);
		}finally {
			try {
				if(reader != null){
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(connection != null){
				connection.disconnect();				
			}
		}

		return null;
	}

	/**
	 * 获取发票号对应的单据信息
	 * @param invoicenum
	 * @return
	 * @throws DAOException
	 */
	private Map<String, String> getBillcode(String invoicenum) throws DAOException {
		String sql = " select pk, billcode, billmaker from v_zlbpbill where invoiceno = '"+invoicenum+"' ";
		Map<String, String> map = (Map<String, String>) this.dao.executeQuery(sql, new MapProcessor());
		return map;
	}

	/**
	 * 获取单据主键
	 * @param billno
	 * @param pk_org
	 * @param type
	 * @return
	 * @throws DAOException
	 */
	private String getPk(String billno, String pk_org, String type) throws DAOException{
		String pkfield = "1";
		String tablename = "dual";
		if("ar".equals(type)){
			pkfield = "pk_gatherbill";
			tablename = "ar_gatherbill";
		}else if("ap".equals(type)){
			pkfield = "pk_paybill";
			tablename = "ap_paybill";
		}

		String sql1 = " select " + pkfield + " from " + tablename + " where billno = '"+billno+"' and nvl(dr,0)=0";
		String pk = (String)this.dao.executeQuery(sql1, new ColumnProcessor());

		return pk;
	}

	/**
	 * 获取制单人
	 * @param billno
	 * @param pk_org
	 * @param type
	 * @return
	 * @throws DAOException
	 */
	private String getBillMaker(String billno, String pk_org, String type) throws DAOException{
		String pkfield = "1";
		String tablename = "dual";
		if("ar".equals(type)){
			pkfield = "billmaker";
			tablename = "ar_gatherbill";
		}else if("ap".equals(type)){
			pkfield = "billmaker";
			tablename = "ap_paybill";
		}

		String sql1 = " select " + pkfield + " from " + tablename + " where billno = '"+billno+"' and nvl(dr,0)=0";
		String pk = (String)this.dao.executeQuery(sql1, new ColumnProcessor());

		return pk;
	}

	/**
	 * 检查文件是否已经上传
	 * @param fileName
	 * @param pk
	 * @return
	 * @throws Exception
	 */
	private Boolean checkIsSaveName(String fileName, String pk) throws Exception {
		String sql = " select pk from sm_pub_filesystem where dr = 0 and filepath like '%" + pk + "/" + fileName+ "%' and isfolder = 'n'";
		String pk_file = (String)this.dao.executeQuery(sql, new ColumnProcessor());
		if(pk_file == null || pk_file.trim().length() == 0) {
			return false;
		}else{
			//			Logger.error("浙里办票自动上传附件失败, 文件已上传，编号：" + billno);
			return true;
		}
	}

	public static int getfilelimit()
	{
		String pk_org = "GLOBLE00000000000000";
		String limit = "AttachLmt";

		int maxsize = 2;
		try {
			maxsize = SysInitQuery.getParaInt(pk_org, limit).intValue();
		} catch (BusinessException e) {
			Logger.error(e);
		}
		return maxsize;
	}

	/**
	 * 判断文件是否存在，不存在就创建
	 * @param file
	 * @throws Exception 
	 */
	public static void createFile(File file) throws Exception {
		if (file.exists()) {
			System.out.println("File exists");
		} else {
			System.out.println("File not exists, create it ...");
			//getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
			if (!file.getParentFile().exists()) {
				System.out.println("not exists");
				//创建上级目录
				file.getParentFile().mkdirs();
			}
			try {
				//在上级目录里创建文件
				file.createNewFile();
				//				Thread.sleep(2);
			} catch (IOException e) {
				throw new Exception(e.getMessage());
			}
		}
	}
}
